#coding=utf-8
# from flask import Blueprint,url_for,render_template
from bottle import Bottle, Route
from lib.template import tpl

global cache
cache = {}

import sys
reload(sys)
sys.setdefaultencoding('utf8')

url=Bottle()
url.path = 'api'

def route(seturl,method='GET'):
	def decorator(func):
		ro=Route(url, seturl, method, func, name=func.__name__)
		url.add_route(ro)
		return func
	return decorator

class api:
	@staticmethod
	def apireturn(status=200,msg="",data=[]):
		ret={}
		ret['status']=status
		ret['msg']=msg
		ret['data']=data
		return str(ret)

	@staticmethod
	def apiRead(func):
		'''
		name
		接口名称
		bewrite
		接口描述
		field
		product,产品id,备注
		参数名称,参数说明,备注
		return
		200,成功,
		返回值,返回说明,
		returncode
		200,成功,
		返回值,返回说明,
		'''
		returnstr=[]
		for name in dir(func):
			if '__' not in name and 'as_view'!=name and 'decorators'!=name and 'dispatch_request'!=name and 'methods'!=name:
				sr={}
				sr['name']=name
				stmp=eval('func.'+name+'.__doc__')
				stmp=stmp.replace(' ','')
				stmp=stmp.replace('\t','')
				stmp=stmp.split('\n')
				sr['url']=stmp[0]
				doc={}
				field="url"
				doc[field]=[]
				for t in stmp:
					if t=='name' or t=='bewrite' or t=='field' or t=='return' or t=='returncode':
						field=t
						doc[field]=[]
					else:
						if t!="":
							doc[field].append(t.split(','))
				sr['doc']=doc
				returnstr.append(sr)
		def abc():
			for sr in returnstr:
				try:
					sr['url']=url.get_url(sr['name'])
				except Exception, e:
					print e
			# print returnstr
			# return str(returnstr)
			return tpl('api/api', data=returnstr, url=url)
		ro=Route(url,'/help/doc/' + func.__name__,'GET',abc)
		url.add_route(ro)

		global cache
		stmpf = cache
		if stmpf==None:
			stmpf={}
		stmpf[func.__name__]={'url':'/help/doc/'+func.__name__,'doc':str(func.__doc__)}
		cache = stmpf
		return func

@route('/help/doc')
def urlcat():
	stmp=cache
	# print str(stmp)
	return tpl('api/apidoc', data=stmp, url=url)


import bottle
bottle.mount(url.path, url)